const {
  controller
} = require('../controllers/Controller.js');
const url = require("../../utils/kzj.request").url

const app = getApp();



Page({

  /**
   * 页面的初始数据
   */
  data: {
    detail: {},
    payNum: 1,
    totalPrice: 0,
    address: null,
    addressList: [],
    dialogShowAddress: false,
    currentAddressIndex: 0,
    canPay: true,
    isMail: 0,
  },
  onLoad: function (options) {
    const detail = JSON.parse(options.detail)
    const price = detail.price
    const MaxPayNum = detail.num
    let limitNum = (10000 / price - MaxPayNum) > 0 ? MaxPayNum : 10000 / price
    limitNum = limitNum.toFixed(0)

    const totalPrice = price
    this.setData({
      limitNum,
      detail,
      totalPrice
    })
    if (options.invitationAccountId) {
      this.setData({
        invitationAccountId: options.invitationAccountId
      })
    }
    this.getAddressList()
  },

  //加减商品数量
  addSubtract(e) {
    //拼团只能购买一份、一卡通通过payType 控制
    if (this.data.detail.type == 3 || this.data.detail.payType  == 1 ) { 
      wx.showToast({
        title: '单次仅可购买一份',
        icon: 'none'
      })
      return
    }
    let type = e.currentTarget.dataset['type'];
    let payNum = this.data.payNum
    const limitNum = this.data.limitNum
    if (type == "add") {
      payNum++
    } else if (payNum > 1) {
      payNum--
    }
    if (payNum > limitNum) {
      wx.showToast({
        title: '不可超过限购数',
        icon: 'none'
      })
      payNum = limitNum
    }

    const price = this.data.detail.price
    let totalPrice = payNum * price
    totalPrice = totalPrice.toFixed(2)

    this.setData({
      payNum,
      totalPrice
    })

  },
  changenums(e) {
    const limitNum = this.data.limitNum
    let payNum = Number(e.detail.value)
    if (payNum > limitNum) {
      wx.showToast({
        title: '不可超过限购数',
        icon: 'none'
      })
      payNum = limitNum
    }
    const price = this.data.detail.price
    let totalPrice = payNum * price
    totalPrice = totalPrice.toFixed(2)
    this.setData({
      payNum,
      totalPrice
    })
  },





  tapDialogButton(e) {
    let index = e.detail.index
    let that = this
    wx.requestSubscribeMessage({
      tmplIds: ['_uuqoPgxng4xi9Zfhr3xt41_NQrso8WTCUn6M9JoGYs'],
      success: res => {
        console.log(res)
      },
      complete: () => {
        if (index == 1) {
          if (that.data.isGood) {
            that.goodPay()
          } else {
            that.cartPay()
          }
        } else {

        }
      }
    })
    this.setData({
      dialogShow: false
    })
  },

  //打开地址弹窗
  toSelectAddress() {
    this.setData({
      dialogShowAddress: true
    })
  },
  toAddressPage() {
    wx.navigateTo({
      url: '/pages/my/my-index/selectAddress',
    })
  },
  changeAddress(e) {
    let index = e.currentTarget.dataset.index
    this.setData({
      currentAddressIndex: index
    })
  },
  closeAddress() {
    this.setData({
      dialogShowAddress: false
    })
  },
  handleAddress() {
    let index = this.data.currentAddressIndex
    const address = this.data.addressList[index]
    this.setData({
      address
    })
    this.closeAddress()
  },

  //获取地址列表
  getAddressList() {
    controller.getAddressList().then(res => {
      if (res.data) {
        let address = null
        if (res.data[0].isChoice) { //默认地址添加
          address = res.data[0]
        }
        this.setData({
          address,
          addressList: res.data,
        })
      }
    })
  },
  //是否需要配送地址
  isAddress(e) {
    let isMail = e.currentTarget.dataset.ismail
    this.setData({
      isMail: isMail
    })
  },




  //生成订单购买
  createCouponOrder() {
    let that = this
    if (this.data.canPay == false) {
      return
    }

    let value = {}
    let orderUrl = ''
    const type = this.data.detail.type
    if (type == 0 || type == 2) { //一卡通、爆品
      if (this.data.invitationAccountId) {
        value.invitationAccountId = this.data.invitationAccountId
      }
      value.num = this.data.payNum
      orderUrl = "/api/order/couponOrder"
    } else { //拼团
      orderUrl = "/api/order/shopGroupPinOrder"
    }

    const isMail = this.data.isMail
    if (isMail) {
      if (this.data.address) {
        value.addressId = this.data.address.id
      } else {
        wx.showToast({
          icon: "none",
          title: '请选择收货地址',
        })
        return
      }
    }
    value.isMail = isMail
    value.couponBagId = this.data.detail.id
    value.sessionId = wx.getStorageSync('usertoken')
    this.setData({
      canPay: false
    })
    wx.request({
      url: url + orderUrl,
      method: 'POST',
      data: value,
      header: {
        'Content-Type': 'application/x-www-form-urlencoded'
      },
      success(res) {
        if (res.statusCode == 200) {
          that.setData({
            canPay: true
          })
          if (res.data.code == 1) {
            let data = res.data.data
            that.pay(data)
          } else if (res.data.code == 2) {
            wx.setStorageSync('usertoken', '')
          } else if (res.data.code == 3) {
            wx.setStorageSync('usertoken', '')
          } else {
            wx.showToast({
              title: res.data.desc,
              icon: 'none',
              duration: 800
            });
          }
        } else {
          wx.showToast({
            title: '[' + res.code + '] 服务器出错,请重试',
            icon: 'none',
            duration: 800
          });
        }
      }
    })

  },
  //生成拼团购买
  createGroupWorkOrder() {
    let that = this
    if (this.data.canPay == false) {
      return
    }
    let value = {}
    value.couponBagId = this.data.detail.id
    value.sessionId = wx.getStorageSync('usertoken')
    this.setData({
      canPay: false
    })
    wx.request({
      url: url + "/api/order/shopGroupPinOrder",
      method: 'POST',
      data: value,
      header: {
        'Content-Type': 'application/x-www-form-urlencoded'
      },
      success(res) {
        if (res.statusCode == 200) {
          that.setData({
            canPay: true
          })
          if (res.data.code == 1) {
            let data = res.data.data
            that.pay(data)
          } else if (res.data.code == 2) {
            wx.setStorageSync('usertoken', '')
          } else if (res.data.code == 3) {
            wx.setStorageSync('usertoken', '')
          } else {
            wx.showToast({
              title: res.data.desc,
              icon: 'none',
              duration: 800
            });
          }
        } else {
          wx.showToast({
            title: '[' + res.code + '] 服务器出错,请重试',
            icon: 'none',
            duration: 800
          });
        }
      }
    })
  },
  pay(data) {
    let that = this
    let value = {}
    value.openId = app.globalData.openId
    value.orderNo = data.orderNo
    value.type = "GC"
    controller.weChatPay(value).then(res => {
      let data = JSON.parse(res.data)
      wx.requestPayment({
        nonceStr: data.nonceStr,
        package: data.package,
        paySign: data.paySign,
        timeStamp: data.timeStamp,
        signType: data.signType,
        success(res) {
          wx.showToast({
            title: "支付成功",
            icon: 'none',
            duration: 1000
          });
          if (that.data.detail.type == 3) {

          } else {
            setTimeout(function () {
              wx.showActionSheet({
                itemList: ['去查看', '继续浏览'],
                success(res) {
                  let index = res.tapIndex
                  console.log(res)
                  if (index == 0) {
                    console.log(that.data.detail.type);
                    wx.reLaunch({
                      url: '/pages/myCenter/myCenter?type=' + that.data.detail.type,
                    })
                  } else {
                    wx.reLaunch({
                      url: '/pages/TradingArea/moreShopCircle?id=' + that.data.detail.shopGroupId,
                    })
                  }
                },
                fail(res) {
                  console.log(res.errMsg)
                }
              })
            }, 1500)
          }
        },
        fail(res) {
          wx.showToast({
            title: "支付失败",
            icon: 'none',
            duration: 1000
          });
        },
        complete() {
          that.setData({
            canPay: true
          })
        }
      })
    })
  },
})